package com.jfirer.mvc.resolver.impl;

import com.jfirer.baseutil.StringUtil;
import com.jfirer.baseutil.reflect.ReflectUtil;
import com.jfirer.mvc.annotation.MvcDateParse;
import com.jfirer.mvc.resolver.AbstractParamResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateResolver extends AbstractParamResolver
{
    private final String pattern;

    public DateResolver(String paramName, Annotation[] annotations)
    {
        super(paramName);
        String t_pattern = "yyyy-MM-dd";
        for (Annotation each : annotations)
        {
            if (each instanceof MvcDateParse)
            {
                t_pattern = ((MvcDateParse) each).date_format();
            }
        }
        pattern = t_pattern;
    }

    @Override
    public Object resolve(HttpServletRequest request, HttpServletResponse response)
    {
        String value = request.getParameter(paramName);
        if (StringUtil.isNotBlank(value))
        {
            SimpleDateFormat format = new SimpleDateFormat(pattern);
            try
            {
                return new Date(format.parse(value).getTime());
            }
            catch (ParseException e)
            {
                ReflectUtil.throwException(e);
                return null;
            }
        }
        else
        {
            return null;
        }
    }
}
